const puppeteer = require('puppeteer');
const sleep = time => new Promise(resolve => {
  setTimeout(resolve, time)
})

;
(async () => {
  const browser = await puppeteer.launch({
    headless: false, //代码运行时打开浏览器方便观察
    args: ['--no-sandbox'],
    dumpio: false
  })
  const page = await browser.newPage()

  await page.goto('https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=puppeteer%20%E7%99%BB%E5%BD%95%E7%88%AC%E6%95%B0%E6%8D%AE&oq=puppeteer%2520%25E7%2599%25BB%25E5%25BD%2595%25E7%2588%25AC%25E6%2595%25B0%25E6%258D%25AE&rsv_pq=9c76443200004cda&rsv_t=beeag8JIZCo9zwOh8aMZFUctc4u%2BU2438j71VJHa39tv1m%2BtWXnRXUevzrg&rqlang=cn&rsv_enter=0&rsv_dl=tb&inputT=1026710&rsv_sug3=67&rsv_sug4=1026710', {
    waitUntil: 'networkidle2'
  })

  await page.setViewport({
    width: 1522,
    height: 706
  })
  // await sleep(3000)
  await page.waitForSelector('.s_form #su')
  // await sleep(3000)
  await page.click('.s_form #su')
  const result = await page.evaluate(() => {
    var $ = window.$
    var items = $('#content_left > .c-container')
    var info_arr = []
    // console.log(item, index)
    if (items.length >= 1) {
      items.each((index, item) => {
        // console.log(item, index)
        let id = $(item).attr('id')
        let title = $(item).find('.t > a').text()
        let detail_url = $(item).find('.t > a').attr('href')
        let info_time = $(item).find('.c-abstract > .newTimeFactor_before_abs').text()
        let website = $(item).find('.f13 > a').attr('href')
        let website_icon = $(item).find('.f13 > a > span > img').attr('src')
        info_arr.push({
          id,
          title,
          detail_url,
          info_time,
          website,
          website_icon
        })
      })
    }
    return info_arr;
  })

  // await browser.close()
  console.log(result)
})()